package com.xjtu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xjtu.dto.MedicalVisitDto;
import com.xjtu.entity.CapabilityAssessment;
import com.xjtu.entity.MedicalVisitRecord;
import com.xjtu.exception.BaseException;
import com.xjtu.mapper.MedicalVisitRecordMapper;
import com.xjtu.result.PageResult;
import com.xjtu.result.Result;
import com.xjtu.service.MedicalVisitService;
import com.xjtu.vo.GetMedicalVisitByIdVo;
import lombok.extern.slf4j.Slf4j;
import com.xjtu.vo.MedicalVisitVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class MedicalVisitServiceImpl implements MedicalVisitService {

    @Autowired(required = false)
    MedicalVisitRecordMapper medicalVisitRecordMapper;
    @Override
    public void insert(MedicalVisitDto medicalVisitDto) {
        log.info("新增参数为{}",medicalVisitDto);

        MedicalVisitRecord medicalVisitRecord = new MedicalVisitRecord();
        BeanUtils.copyProperties(medicalVisitDto, medicalVisitRecord);
        log.info("新增记录为{}",medicalVisitRecord);
        medicalVisitRecordMapper.insert(medicalVisitRecord);
        if( medicalVisitRecord.getVisitId() == 0) {
           throw new RuntimeException("插入失败");
        }
    }

    @Override
    public GetMedicalVisitByIdVo queryByVisitId(Long visitId) {
        MedicalVisitRecord medicalVisitRecord = medicalVisitRecordMapper.selectByPrimaryKey(visitId);
        if (medicalVisitRecord == null){
            throw new BaseException("就诊记录不存在");
        }
        GetMedicalVisitByIdVo resp = new GetMedicalVisitByIdVo();
        BeanUtils.copyProperties(medicalVisitRecord,resp);
        return resp;
    }

    @Override
    public void deleteVisitById(Long visitId) {
        log.info("待删除的记录为{}",visitId);
        int num = medicalVisitRecordMapper.deleteByPrimaryKey(visitId);
        if(num == 0) {
            throw new BaseException("删除失败或记录不存在");
        }
    }

    @Override
    public PageResult queryAll(Integer page, Integer perPage, String elderlyName) {

        System.out.println("page = " + page + ", perPage = " + perPage + ", elderlyName = " + elderlyName);

        PageHelper.startPage(page, perPage);
        List<MedicalVisitVo> medicalVisitVos = elderlyName.equals("null") ? medicalVisitRecordMapper.selectAllElderInfo() :medicalVisitRecordMapper.selectElderInfoById(elderlyName);

        System.out.println(medicalVisitVos);

        PageInfo<MedicalVisitVo> pageInfo = new PageInfo<>(medicalVisitVos);
        System.out.println("pageInfo = " + pageInfo);

        long total = pageInfo.getTotal();
        List<MedicalVisitVo> records = pageInfo.getList();
        return new PageResult(total, records);

    }
}
